'use client';

import React, { useState, useEffect } from 'react';
import { SDTemplate, TemplateType } from '@/types/templates';
import styles from './test.module.scss';

interface ApiResponse<T> {
  success: boolean;
  data?: T;
  error?: string;
  total?: number;
  page?: number;
  pageSize?: number;
}

const TestPage: React.FC = () => {
  const [templates, setTemplates] = useState<SDTemplate[]>([]);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    type: 'txt2img' as TemplateType,
    image: '',
    base_model: '',
    lora_model: '',
    lora_output_name: '',
    lora_weight: 0.8,
    vae: '',
    prompt: '',
    negative_prompt: '',
    sampler_name: 'DPM++ 2M Karras',
    steps: 20,
    cfg_scale: 7.0,
    width: 1024,
    height: 1024,
    seed: -1,
    batch_count: 1,
    batch_size: 1,
    // img2img 特有字段
    denoising_strength: 0.75,
    // postprocess 特有字段
    upscaling_resize: 2,
    upscaler_1: 'R-ESRGAN 4x+',
    upscaler_2: 'None',
    extras_upscaler_2_visibility: 0
  });

  // 获取模板列表
  const fetchTemplates = async () => {
    setLoading(true);
    try {
      const response = await fetch('/api/templates-db');
      const result: ApiResponse<SDTemplate[]> = await response.json();
      
      if (result.success && result.data) {
        setTemplates(result.data);
        setMessage(`成功获取 ${result.data.length} 个模板`);
      } else {
        setMessage(`获取失败: ${result.error}`);
      }
    } catch (error: any) {
      setMessage(`请求失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 创建模板
  const createTemplate = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    
    try {
      // 根据类型过滤字段
      const templateData: any = {
        name: formData.name,
        description: formData.description,
        type: formData.type,
        image: formData.image.startsWith('/') ? formData.image : `/${formData.image}`,
        base_model: formData.base_model,
        lora_model: formData.lora_model,
        lora_output_name: formData.lora_output_name,
        lora_weight: formData.lora_weight,
        vae: formData.vae,
        prompt: formData.prompt,
        negative_prompt: formData.negative_prompt,
        sampler_name: formData.sampler_name,
        steps: formData.steps,
        cfg_scale: formData.cfg_scale,
        width: formData.width,
        height: formData.height,
        seed: formData.seed,
        batch_count: formData.batch_count,
        batch_size: formData.batch_size
      };

      // 添加类型特有字段
      if (formData.type === 'img2img') {
        templateData.denoising_strength = formData.denoising_strength;
      } else if (formData.type === 'postprocess') {
        templateData.upscaling_resize = formData.upscaling_resize;
        templateData.upscaler_1 = formData.upscaler_1;
        templateData.upscaler_2 = formData.upscaler_2;
        templateData.extras_upscaler_2_visibility = formData.extras_upscaler_2_visibility;
      }

      const response = await fetch('/api/templates-db', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ template: templateData })
      });

      const result: ApiResponse<SDTemplate> = await response.json();
      
      if (result.success) {
        setMessage(`模板创建成功: ${result.data?.name}`);
        // 重新获取列表
        await fetchTemplates();
        // 重置表单
        setFormData({
          ...formData,
          name: '',
          description: '',
          prompt: '',
          negative_prompt: ''
        });
      } else {
        setMessage(`创建失败: ${result.error}`);
      }
    } catch (error: any) {
      setMessage(`请求失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 删除模板
  const deleteTemplate = async (id: string, name: string) => {
    if (!confirm(`确定要删除模板 "${name}" 吗？`)) {
      return;
    }

    setLoading(true);
    try {
      const response = await fetch(`/api/templates-db/${id}`, {
        method: 'DELETE'
      });

      const result = await response.json();
      
      if (result.success) {
        setMessage(`模板删除成功: ${name}`);
        await fetchTemplates();
      } else {
        setMessage(`删除失败: ${result.error}`);
      }
    } catch (error: any) {
      setMessage(`请求失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 一键清空所有模板
  const clearAllTemplates = async () => {
    if (!confirm('确定要清空所有模板数据吗？此操作不可恢复！')) {
      return;
    }

    setLoading(true);
    try {
      const response = await fetch('/api/templates-db', {
        method: 'DELETE'
      });

      const result = await response.json();
      
      if (result.success) {
        setMessage('所有模板数据已清空');
        await fetchTemplates();
      } else {
        setMessage(`清空失败: ${result.error}`);
      }
    } catch (error: any) {
      setMessage(`请求失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 页面加载时获取数据
  useEffect(() => {
    fetchTemplates();
  }, []);

  return (
    <div className={styles.container}>
      <h1 className={styles.title}>SD模板管理测试页面</h1>
      
      {/* 状态消息 */}
      {message && (
        <div className={`${styles.message} ${message.includes('失败') ? styles.error : styles.success}`}>
          {message}
        </div>
      )}

      <div className={styles.content}>
        {/* 创建表单 */}
        <div className={styles.section}>
          <h2>创建模板</h2>
          <form onSubmit={createTemplate} className={styles.form}>
            <div className={styles.row}>
              <div className={styles.field}>
                <label>模板名称 *</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData({...formData, name: e.target.value})}
                  required
                />
              </div>
              <div className={styles.field}>
                <label>模板类型 *</label>
                <select
                  value={formData.type}
                  onChange={(e) => setFormData({...formData, type: e.target.value as TemplateType})}
                >
                  <option value="txt2img">Text to Image</option>
                  <option value="img2img">Image to Image</option>
                  <option value="postprocess">Post Process</option>
                </select>
              </div>
            </div>

            <div className={styles.field}>
              <label>描述</label>
              <textarea
                value={formData.description}
                onChange={(e) => setFormData({...formData, description: e.target.value})}
                rows={3}
              />
            </div>

            <div className={styles.row}>
              <div className={styles.field}>
                <label>图片路径 *</label>
                <input
                  type="text"
                  value={formData.image}
                  onChange={(e) => setFormData({...formData, image: e.target.value})}
                  placeholder="/path/to/image.jpg"
                  required
                />
              </div>
              <div className={styles.field}>
                <label>基础模型 *</label>
                <input
                  type="text"
                  value={formData.base_model}
                  onChange={(e) => setFormData({...formData, base_model: e.target.value})}
                  placeholder="sd_xl_base_1.0.safetensors"
                  required
                />
              </div>
            </div>

            <div className={styles.row}>
              <div className={styles.field}>
                <label>LORA模型</label>
                <input
                  type="text"
                  value={formData.lora_model}
                  onChange={(e) => setFormData({...formData, lora_model: e.target.value})}
                  placeholder="lora_model.safetensors"
                />
              </div>
              <div className={styles.field}>
                <label>LORA权重</label>
                <input
                  type="number"
                  step="0.1"
                  min="0"
                  max="2"
                  value={formData.lora_weight}
                  onChange={(e) => setFormData({...formData, lora_weight: parseFloat(e.target.value)})}
                />
              </div>
            </div>

            <div className={styles.field}>
              <label>正向提示词 *</label>
              <textarea
                value={formData.prompt}
                onChange={(e) => setFormData({...formData, prompt: e.target.value})}
                rows={3}
                placeholder="描述你想要生成的图像..."
                required
              />
            </div>

            <div className={styles.field}>
              <label>负向提示词</label>
              <textarea
                value={formData.negative_prompt}
                onChange={(e) => setFormData({...formData, negative_prompt: e.target.value})}
                rows={2}
                placeholder="描述你不想要的元素..."
              />
            </div>

            <div className={styles.row}>
              <div className={styles.field}>
                <label>采样器</label>
                <select
                  value={formData.sampler_name}
                  onChange={(e) => setFormData({...formData, sampler_name: e.target.value})}
                >
                  <option value="DPM++ 2M Karras">DPM++ 2M Karras</option>
                  <option value="Euler a">Euler a</option>
                  <option value="DDIM">DDIM</option>
                </select>
              </div>
              <div className={styles.field}>
                <label>步数</label>
                <input
                  type="number"
                  min="1"
                  max="150"
                  value={formData.steps}
                  onChange={(e) => setFormData({...formData, steps: parseInt(e.target.value)})}
                />
              </div>
              <div className={styles.field}>
                <label>CFG Scale</label>
                <input
                  type="number"
                  step="0.5"
                  min="1"
                  max="30"
                  value={formData.cfg_scale}
                  onChange={(e) => setFormData({...formData, cfg_scale: parseFloat(e.target.value)})}
                />
              </div>
            </div>

            <div className={styles.row}>
              <div className={styles.field}>
                <label>宽度</label>
                <input
                  type="number"
                  step="64"
                  min="64"
                  max="2048"
                  value={formData.width}
                  onChange={(e) => setFormData({...formData, width: parseInt(e.target.value)})}
                />
              </div>
              <div className={styles.field}>
                <label>高度</label>
                <input
                  type="number"
                  step="64"
                  min="64"
                  max="2048"
                  value={formData.height}
                  onChange={(e) => setFormData({...formData, height: parseInt(e.target.value)})}
                />
              </div>
            </div>

            {/* img2img 特有字段 */}
            {formData.type === 'img2img' && (
              <div className={styles.field}>
                <label>去噪强度</label>
                <input
                  type="number"
                  step="0.05"
                  min="0"
                  max="1"
                  value={formData.denoising_strength}
                  onChange={(e) => setFormData({...formData, denoising_strength: parseFloat(e.target.value)})}
                />
              </div>
            )}

            {/* postprocess 特有字段 */}
            {formData.type === 'postprocess' && (
              <div className={styles.row}>
                <div className={styles.field}>
                  <label>放大倍数</label>
                  <input
                    type="number"
                    min="1"
                    max="8"
                    value={formData.upscaling_resize}
                    onChange={(e) => setFormData({...formData, upscaling_resize: parseInt(e.target.value)})}
                  />
                </div>
                <div className={styles.field}>
                  <label>放大器1</label>
                  <select
                    value={formData.upscaler_1}
                    onChange={(e) => setFormData({...formData, upscaler_1: e.target.value})}
                  >
                    <option value="R-ESRGAN 4x+">R-ESRGAN 4x+</option>
                    <option value="ESRGAN_4x">ESRGAN_4x</option>
                    <option value="SwinIR_4x">SwinIR_4x</option>
                  </select>
                </div>
              </div>
            )}

            <button type="submit" disabled={loading} className={styles.submitBtn}>
              {loading ? '创建中...' : '创建模板'}
            </button>
          </form>
        </div>

        {/* 数据列表 */}
        <div className={styles.section}>
          <div className={styles.sectionHeader}>
            <h2>模板列表</h2>
            <div className={styles.buttonGroup}>
              <button onClick={fetchTemplates} disabled={loading} className={styles.refreshBtn}>
                {loading ? '加载中...' : '刷新'}
              </button>
              <button onClick={clearAllTemplates} disabled={loading} className={styles.clearBtn}>
                {loading ? '清空中...' : '一键清空'}
              </button>
            </div>
          </div>
          
          {templates.length === 0 ? (
            <div className={styles.empty}>暂无数据</div>
          ) : (
            <div className={styles.table}>
              <div className={styles.tableHeader}>
                <div>ID</div>
                <div>名称</div>
                <div>类型</div>
                <div>描述</div>
                <div>创建时间</div>
                <div>操作</div>
              </div>
              {templates.map((template) => (
                <div key={template.id} className={styles.tableRow}>
                  <div className={styles.id}>{template.id}</div>
                  <div className={styles.name}>{template.name}</div>
                  <div className={styles.type}>
                    <span className={`${styles.badge} ${styles[template.type]}`}>
                      {template.type}
                    </span>
                  </div>
                  <div className={styles.description}>{template.description}</div>
                  <div className={styles.time}>
                    {template.created_at ? new Date(template.created_at).toLocaleString() : '未知'}
                  </div>
                  <div className={styles.actions}>
                    <button
                      onClick={() => deleteTemplate(template.id, template.name)}
                      className={styles.deleteBtn}
                      disabled={loading}
                    >
                      删除
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default TestPage;